<template>
  <contextHolder></contextHolder>
</template>

<script setup lang="tsx">
import { computed, h, inject, ref, watch } from 'vue';
import { audioRefKey } from '@/constants/injectKey';
import { ExclamationCircleFilled } from '@ant-design/icons-vue';
import { useEventSource } from '@boeyo/hooks';
import { useUserStore } from '@boeyo/portal';
import { useDicts } from '@boeyo/portal';
import { Button, Space, notification } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import playIcon from '/static/audio/noise.svg';
import pauseIcon from '/static/audio/pause.svg';

const audioRef = inject(audioRefKey);
const userStore = useUserStore();
const userId = computed(() => userStore.user.userId);

const url = computed(() => `/api/alarmPush/sse/connect/${userId.value}`);
const method = computed<'GET' | 'POST' | 'PUT' | 'DELETE'>(() => 'GET' as any);
const localMessage = ref([]);
// 获取告警类型
const dictArr = ['alarm_type'];
const { alarmTypeEnum } = useDicts(dictArr);

// 连接SSE
const _opt = computed(() => {
  return {
    headers: {
      ['Authorization']: `Bearer ${userStore.token}`,
      'Content-Type': 'application/json',
      Accept: '*/*',
    },
    withCredentials: false,
    method: method.value,
    onMessage(res) {
      try {
        const data = JSON.parse(res);
        localMessage.value.unshift(data);
      } catch (error) {}
    },
    onError(err) {
      console.log('告警弹窗SSE连接错误-----------', err);
    },
  };
});
const { connect } = useEventSource(url, _opt);

watch(
  () => userId.value,
  () => {
    if (userId.value) {
      connect();
    }
  },
  {
    immediate: true,
  },
);
const [api, contextHolder] = notification.useNotification();

// 是否展示小喇叭
const showPlayArr = ref<Array<boolean>>([]);
const handleMessage = () => {
  if (localMessage.value.length) {
    openNotification();
    const { content, isHaveSound } = localMessage.value[0];

    if (isHaveSound !== '1') {
      showPlayArr.value.unshift(false);
      return;
    }
    showPlayArr.value.unshift(true);
    audioRef?.value?.play();
  }
};

// 上一条下一条
const current = ref(0);

const prev = () => {
  if (current.value > 0) {
    current.value--;
    openNotification();
  }
};
const next = () => {
  if (current.value < localMessage.value.length) {
    current.value++;
    openNotification();
  }
};
// 1 提示 2 普通 3警告
const isPlay = ref(true);
const openNotification = () => {
  const data = localMessage.value[current.value];
  if (data) {
    // const color = LevelColor[data.alarmLevel];
    // color,
    const icon = () => {
      return h(ExclamationCircleFilled, {
        style: {
          fontSize: '36px',
        },
      });
    };
    const message = () => (
      // color,
      <div
        style={{
          paddingLeft: '12px',
          fontWeight: 700,
          fontSize: '16px',
          display: 'flex',
        }}
      >
        {`${alarmTypeEnum.value[data.alarmType]?.text}`}
        &nbsp;
        {showPlayArr.value?.[current.value] ? (
          <img
            src={isPlay.value ? playIcon : pauseIcon}
            alt='noise'
            onClick={onNoise}
          />
        ) : null}
      </div>
    );
    const onNoise = () => {
      isPlay.value ? audioRef?.value?.pause() : audioRef?.value?.play();
      isPlay.value = !isPlay.value;
    };

    const content = () => {
      return (
        <div class='overflow-auto text-sm leading-[22px]'>
          {data.description.split('\n').map((item: string) => {
            return <div>{item}</div>;
          })}
        </div>
      );
    };
    const key = 'NOTICE_MESSAGE_KEY';
    api.warning({
      class: 'custom-notice',
      icon,
      message,
      description: content,
      placement: 'bottomRight',
      key,
      duration: null,
      btn() {
        return localMessage.value.length > 1 ? (
          <Space>
            <Button
              type='primary'
              onClick={() => gotoAlarmPage()}
              class='view-btn mr-16'
            >
              查看
            </Button>
            <span>
              {current.value + 1} / {localMessage.value.length}
            </span>
            <Button
              type='link'
              disabled={current.value === 0}
              onClick={() => prev()}
            >
              上一条
            </Button>
            <Button
              type='link'
              disabled={current.value + 1 === localMessage.value.length}
              onClick={() => next()}
            >
              下一条
            </Button>
          </Space>
        ) : (
          <Button type='primary' onClick={() => gotoAlarmPage()}>
            查看
          </Button>
        );
      },
      onClose: () => {
        localMessage.value = [];
        // 关闭声音
        audioRef?.value?.pause();
      },
    });
  }
};

/**
 * 跳转到告警页面
 */
const router = useRouter();
const gotoAlarmPage = () => {
  router.push({
    path: '/alarm/alarm-list',
  });
};

watch(
  () => localMessage.value,
  () => {
    handleMessage();
  },
  {
    deep: true,
  },
);
</script>

<style lang="scss">
.custom-notice {
  width: 402px;
  height: 242px;
  padding: 18px;
  background: linear-gradient(180deg, #0d4975 0%, #3885bc 100%) !important;
  box-shadow: 0px 0px 16px 4px rgba(41, 114, 187, 0.6);
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #38acff;

  .ant-notification-notice-with-icon {
    height: 100%;
    // 告警弹窗图标颜色
    .anticon-exclamation-circle {
      color: #ff7d93;
    }
    .ant-notification-notice-description {
      height: 140px;
      .text-sm {
        height: 100%;
        overflow-y: auto;
      }
    }
    .ant-notification-notice-btn {
      margin-top: 6px;
    }
  }

  .ant-btn-link:disabled {
    color: rgba(255, 255, 255, 0.5);
  }

  .ant-notification-notice-message {
    color: #ff7d93;
  }

  .ant-btn-primary {
    background: #69a7d4;
    &:hover {
      background: #38c3ff;
    }
  }
}
</style>
